package com.atguigu.paymentdemo.service.impl;

import com.atguigu.paymentdemo.entity.PaymentInfo;
import com.atguigu.paymentdemo.enums.PayType;
import com.atguigu.paymentdemo.mapper.PaymentInfoMapper;
import com.atguigu.paymentdemo.service.PaymentInfoService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    /**
     * 记录支付日志根据明文
     * @param plainText
     */
    @Override
    public void createPatmentInfo(String plainText) {
        log.info("记录支付日志...");
        Gson gson = new Gson();
        HashMap plainTextMap = gson.fromJson(plainText, HashMap.class);
        // 订单号
        String orderNo = (String) plainTextMap.get("out_trade_no");
        // 交易流水业务编号
        String transactionId = (String) plainTextMap.get("transaction_id");
        // 支付类型
        String tradeType = (String) plainTextMap.get("trade_type");
        // 交易状态
        String tradeState = (String) plainTextMap.get("trade_state");
        // 用户实际支付的金额
        Map<String, Object> amount = (Map<String, Object>) plainTextMap.get("amount");

        // 先转为double 再转为int才行
        Integer payerTotal = ((Double) amount.get("payer_total")).intValue();

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentType(PayType.WXPAY.getType());
        //
        paymentInfo.setTransactionId(transactionId);
        paymentInfo.setTradeType(tradeType);
        paymentInfo.setTradeState(tradeState);
        paymentInfo.setPayerTotal(payerTotal);
        paymentInfo.setContent(plainText);

        save(paymentInfo);
    }

    /**
     * 根据订单号查询到这个用户的支付类型
     * @param orderNo
     */
    @Override
    public PaymentInfo getPaymentTypeByOrderNo(String orderNo) {
        LambdaQueryWrapper<PaymentInfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(PaymentInfo::getOrderNo, orderNo);
        PaymentInfo paymentInfo = getOne(lambdaQueryWrapper);
        return paymentInfo;
    }
}
